package com.own.business.wechat.base.service.impl;

import com.own.business.wechat.base.entity.bo.WechatUserBo;
import com.own.business.wechat.base.entity.map.WechatUserMapVo;
import com.own.business.wechat.base.entity.po.WechatUser;
import com.own.business.wechat.base.entity.query.WechatUserQuery;
import com.own.business.wechat.base.entity.vo.WechatUserVo;
import com.own.business.wechat.base.mapper.WechatUserMapper;
import com.own.business.wechat.base.service.WechatUserService;
import com.own.component.common.base.service.impl.AbstractBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.function.Consumer;

/**
 * WechatUserServiceImpl
 *
 * @author chenxueli
 * @date 2023-06-29 22:28:56
 */
@Slf4j
@Service
public class WechatUserServiceImpl extends AbstractBaseService<
        WechatUser,
        WechatUserBo,
        WechatUserVo,
        WechatUserMapVo,
        WechatUserQuery,
        WechatUserMapper
        > implements WechatUserService {

    @Resource
    private WechatUserMapper wechatUserMapper;

    /**
     * 保存微信用户信息
     *
     * @param appId    应用id
     * @param openId   微信用户唯一标识
     * @param consumer 解析获取微信用户信息的方法
     * @return 微信用户信息
     */
    @Override
    public WechatUser save(String appId, String openId, Consumer<WechatUser> consumer) {
        // 查询有没有用户信息
        var wrapper = lambdaQueryWrapper()
                .eq(WechatUser::getAppId, appId)
                .eq(WechatUser::getOpenId, openId);
        var old = getOneByWrapper(wrapper);
        if (old != null) {
            // 修改信息
            consumer.accept(old);
            wechatUserMapper.updateById(old);
            return old;
        }
        // 新增信息
        var po = new WechatUser();
        po.setOpenId(openId);
        po.setAppId(appId);
        consumer.accept(po);
        wechatUserMapper.insert(po);
        return po;
    }

}
